//
//  MoonHTTPRequest.m
//  DirectSeller
//
//  Created by 王 文彬 on 13-9-22.
//  Copyright (c) 2013年 Chongqing Fenrir Technology Co., Ltd. All rights reserved.
//

#import "MoonHTTPRequest.h"
#import "config.h"
#import "MKNetworkKit.h"
#import <Foundation/Foundation.h>


@implementation MoonHTTPRequest

@synthesize HTTPBodyFormat  = _HTTPBodyFormat;
@synthesize delegate        = _delegate;
@synthesize errorMessage    = _errorMessage;

@synthesize successSelector = _successSelector;
@synthesize failureSelector = _failurSelector;

@synthesize clientCertificate = _clientCertificate;
@synthesize clientCertificatePassword = _clientCertificatePassword;

@synthesize progressTitle      = _progressTitle;
@synthesize progressDetailText = _progressDetailText;

- (id)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}


//- (id)initWithURL:(NSURL *)URL
//{
//    self = [super init];
//    if (self) {
//        
//        _URL = URL;
//    }
//    return self;
//}


- (id)initWithURLString:(NSString *)URLString
{
    self = [super init];
    if (self) {
        
        _URLString = URLString;
    }
    return self;
}


- (NSMutableDictionary *)parameters
{
    if (_HTTPParameters == Nil) {
        
        _HTTPParameters = [[NSMutableDictionary alloc] init];
    }
    
    if (!_HTTPParameters[@"token"]) {
        [_HTTPParameters setValue:_ACCOUNT_TOKEN forKey:@"token"];
    }
    else if (_HTTPParameters[@"token"] != nil && [_HTTPParameters[@"token"] isEqualToString:@""]) {
        [_HTTPParameters removeObjectForKey:@"token"];
    }
    
    if (!_HTTPParameters[@"appKey"]) {
        [_HTTPParameters setValue:_CONFIG_APP_KEY forKey:@"appKey"];
    }
    
    return _HTTPParameters;
}


- (void)addParameters:(NSDictionary *)parameters
{
    
    [self.parameters addEntriesFromDictionary:parameters];
}


- (void)setParameter:(NSObject *)parameter forName:(NSString *)parameterName
{
    if (parameter != Nil)
    {
        [self.parameters setObject:parameter forKey:parameterName];
    }
}


- (void)onSuccess:(SuccessBlock)success onFailure:(FailureBlock)failure
{
    if (success) {
        
        _successBlock = success;
    }
    
    if (failure) {
        
        _failureBlock = failure;
    }
}


- (void)onSuccess:(SuccessBlock)success
{
    _successBlock = success;
}


- (void)onFailure:(FailureBlock)failure
{
    _failureBlock = failure;
}

- (void)asynchronous
{
    //准备参数，将普通参数和文件参数区分
    NSMutableDictionary* postParams = [[NSMutableDictionary alloc] init];
    NSMutableDictionary* fileParams = [[NSMutableDictionary alloc] init];
    
    //遍历前使用局部变量保存parameter，否则下面的循环每次调用self.parameter时，可能会照成内部元素变化（某个固定元素为空时），而导致线程崩溃。
    //特别是将self.parameter语句写入与MKEngine和MKOperation有关的语句中时
    NSMutableDictionary* params = [NSMutableDictionary dictionaryWithDictionary:self.parameters];

    //遍历，分类收集
    for (id key in params) {
        
        NSObject *dataParam = [params valueForKey:key];
        
        //如果是UIImage
        if ([dataParam isKindOfClass:[UIImage class]]) {

            NSData* imageData = UIImagePNGRepresentation((UIImage *)dataParam);
            [fileParams setObject:imageData forKey:key];
        }
        
        //如果是NSData
        else if ([dataParam isKindOfClass:[NSData class]]) {

            [fileParams setObject:dataParam forKey:key];
        }
        
        //如果是其他类型
        else {
            
            [postParams setObject:dataParam forKey:key];
        }
    }


    //开始请求
    MKNetworkEngine* engine = [[MKNetworkEngine alloc] init];
    MKNetworkOperation* operation = [engine operationWithURLString:_URLString params:postParams httpMethod:@"POST"];  //将普通参数直接放入
//    [operation addHeader:@"Content-Type" withValue:@"multipart/form-data"];
    
    //将文件参数放入。如果有就会遍历
    for (id key in fileParams) {
        
        [operation addData:[fileParams valueForKey:key] forKey:key mimeType:@"image/png" fileName:[NSString stringWithFormat:@"avatr_%@.png", key]];
    }

    //准备证书
    if (_clientCertificate) {
        operation.clientCertificate = _clientCertificate;
        operation.shouldContinueWithInvalidCertificate = true;
    }
    if (_clientCertificatePassword) {
        operation.clientCertificatePassword = _clientCertificatePassword;
    }
    

    //设定请求结果
    [operation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        
        [self performSuccessSelector:completedOperation.responseData];
        [self removeProgressor];
        
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
    
        _errorMessage = [NSString stringWithFormat:@"[%@ %@] Network Request Error:\n--------\n Response \n--------\n%@\n\n--------\n Error \n--------\n%@", [self class], NSStringFromSelector(_cmd), completedOperation.responseString, error];
        [self performFailSelector:error];
        [self removeProgressor];
    }];
    

    //开始异步
    NSLog(@"[%@ %@]%@ %@", [self class], NSStringFromSelector(_cmd), _URLString, params);
    [self showProgressor];
    [engine enqueueOperation:operation];
    
}


// 成功时调用协议方法，如果设置了指定的，就用指定的selector
//
- (void)performSuccessSelector:(NSData *)data
{
    NSError* error;
    NSDictionary* JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    if (error) {

        _errorMessage = [NSString stringWithFormat:@"[%@ %@] JSON Translating Error:\n--------\n Response \n--------\n%@\n\n--------\n Error \n--------\n%@", [self class], NSStringFromSelector(_cmd), [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], error];
        
        [self performFailSelector:error];
        return;
    }
    
    if (_delegate) {
 
        if (_successSelector && [_delegate respondsToSelector:_successSelector]) {
 
            [_delegate performSelector:_successSelector withObject:JSON];
        }
        else if (!_successSelector && [_delegate respondsToSelector:@selector(moonHTTPRequest:didResponse:)]) {
 
            [_delegate performSelector:@selector(moonHTTPRequest:didResponse:) withObject:self withObject:JSON];
        }
    }
    
    if (_successBlock) {
        
        _successBlock(JSON);
    }
}


// 失败时时调用协议方法，如果设置了指定的，就用指定的selector
//
- (void)performFailSelector:(NSError *)error
{
    //如果设定了代理
    if (_delegate) {
 
        //如果也设定了失败时的selector，就调用协议下指定的这个selector
        if (_failureSelector && [_delegate respondsToSelector:_failureSelector]) {
 
            [_delegate performSelector:_failureSelector withObject:error];
        }
        //否则就调用协议默认指定的selector
        else if (!_failureSelector && [_delegate respondsToSelector:@selector(moonHTTPRequest:onError:)]) {
 
            [_delegate performSelector:@selector(moonHTTPRequest:onError:) withObject:self withObject:error];
        }
    }
    
    if (_failureBlock) {
        
        _failureBlock(error);
    }
}


//////////////////////////////////////////////////////////////////////////////////////////
- (void)showProgressor
{
    if (_progressOn == false) {
        
        return;
    }
    
    if (_progressor == nil) {
        
        //有键盘遮罩的问题，一定要建立在最后一个Window上面，不然后被键盘挡住
        UIWindow* window = [[UIApplication sharedApplication].windows objectAtIndex:([UIApplication sharedApplication].windows.count - 1)];
        _progressor = [[MBProgressHUD alloc] initWithWindow:window];
        [window addSubview:_progressor];
    }
    
    _progressor.labelText = _progressTitle;
    _progressor.detailsLabelText = _progressDetailText;

    [_progressor show:true];
}

// 移除hud
//
- (void)removeProgressor
{
    if (_progressOn == true && _progressor != nil) {
        _progressor.hidden = true;
        [_progressor removeFromSuperview];
    }
}


@end
